package com.anlu.activemq.test1;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class ConsumerTopicA {
    private static final String USERNAME
            = ActiveMQConnection.DEFAULT_USER;//默认连接用户名
    private static final String PASSWORD
            = ActiveMQConnection.DEFAULT_PASSWORD;//默认连接密码
    private static final String BROKEURL
            = ActiveMQConnection.DEFAULT_BROKER_URL;//默认连接地址

    public static void main(String[] args) {
        ConnectionFactory connectionFactory = null;
        Connection connection = null;

        Session session;//会话，接受或者发送消息的线程;
        Destination destination;//消息的目的地
        MessageConsumer messageConsumer;//消息的消费者

        //实例化连接工厂
        connectionFactory = new ActiveMQConnectionFactory(ConsumerTopicA.USERNAME,
                ConsumerTopicA.PASSWORD, ConsumerTopicA.BROKEURL);
        try {
            //通过连接工厂获取连接
            connection = connectionFactory.createConnection();
            //启动连接
            connection.start();

            //创建session
            session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            //创建一个HelloWorld的消息队列
            destination = session.createTopic("anlu.test.topic");
            //创建消息的消费者
            messageConsumer = session.createConsumer(destination);
            messageConsumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    try{
                        System.out.println("ConsumerTopicA Accept Msg:"+((TextMessage)message).getText());
                    }catch (JMSException e){
                        e.printStackTrace();
                    }
                }
            });


        } catch (JMSException e) {
            e.printStackTrace();
        }
//        finally {
//            try {
//                if (connection != null) {
//                    connection.close();
//                }
//            } catch (JMSException e) {
//                e.printStackTrace();
//            }
//        }
    }
}
